package top.yueyazhui.dds.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.yueyazhui.dds.datasource.DataSourceType;
import top.yueyazhui.dds.datasource.DynamicDataSourceContextHolder;

import javax.servlet.http.HttpSession;

@Component
@Aspect
@Order(1) // 值越小，执行的优先级越高，业务的优先级相对低
public class GlobalDataSourceAspect {

    @Autowired
    HttpSession session;

    @Pointcut("execution(* top.yueyazhui.dds.service.impl.*.*(..))")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        DynamicDataSourceContextHolder.setDataSource((String) session.getAttribute(DataSourceType.DATA_SOURCE_SESSION_KEY));
        try {
            return proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            DynamicDataSourceContextHolder.removeDataSource();
        }
        return null;
    }
}
